package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop1/models"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) Add() {
	var err error
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	price, _ := c.GetFloat("price")
	type_id, _ := c.GetInt("type_id")

	if name == "" || num == 0 || price == 0.0 || type_id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "添加数据不能为空",
		}
		c.ServeJSON()
		return
	}

	shops := models.Shop{
		Name:   name,
		Num:    num,
		Price:  price,
		TypeId: type_id,
	}

	if shops.Add(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "添加失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 500,
		"mes":  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *ShopController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var shops []models.ShopData
	models.DB.Model(&models.Shop{}).
		Select("shops.*, shop_type_ids.name").
		Joins("join shop_type_ids on shops.type_id = shop_type_ids.id").
		Scan(&shops)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "展示成功",
		"data": shops,
	}
	c.ServeJSON()
	return

}

func (c *ShopController) Update() {
	var err error
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	price, _ := c.GetFloat("price")
	type_id, _ := c.GetInt("type_id")

	shops := models.Shop{
		Name:   name,
		Num:    num,
		Price:  price,
		TypeId: type_id,
	}

	if shops.Update(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"mes":  "修改失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "修改成功",
	}
	c.ServeJSON()

}
func (c *ShopController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	var shops models.Shop
	models.DB.Where("id=?", id).Delete(&shops)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "删除成功",
	}
	c.ServeJSON()
	return
}
